package com.test;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class Item {
	protected Object obj = null;
	boolean ready = false;
	protected JsonKey key ;
	protected Item parent = null;
	Set<SelfAction> readyAction = null;	
	Set<ChildrenAction> childrenAction = null;	
	List<RuleNode> newRules = null;
	
	
	public Item(JsonKey key,Object obj){
		this.obj = obj;
		this.key = key;
	}
	
	public void render(JsonWriter w){
		if(ready){
			doRender(w);
			w.ctx.stack.pop();
		}else{
			doReady(w);
			this.ready = true ;
			
		}
	}
	
	protected void doReady(JsonWriter w){
		
	}
	
	protected void doRender(JsonWriter w){
		
	}
	
	protected boolean findAction(JsonWriter w,Class c ){
		Iterator<RuleNode> rules =w.ctx.scops.ruleIteator();
		
		if(rules!=null){
			
			while(rules.hasNext()){
				RuleNode rule = rules.next();
				MatchResult result = rule.howMatch(this.key, c, obj);
      				if(result==null){
					continue ;
				}
				
				if(result.nextRule!=null){
					if(newRules==null){
						newRules = new ArrayList<RuleNode>();
					}
					newRules.add(result.nextRule);
				}else if(result.action!=null){
					Action a = result.action;
					if(a instanceof ChildrenAction ){
						this.addChildrenAction((ChildrenAction)a);
					}else{
						this.addAction((SelfAction)a);
					}
				}
			}
			
		}
		
		if(readyAction!=null){
			for(SelfAction a:readyAction){
				boolean run = false ;
				run  = a.doIt(w, key, this);
				
				if(!run){
					return false ;
				}
				
			}
		}
		
		return true ;
	}
	
	
	public boolean runChildrenItem(JsonWriter w,JsonKey key ,List<Item> list){
		if(this.childrenAction!=null){
			for(ChildrenAction action:childrenAction){
				boolean running =  action.doIt(w, key, list);
				if(!running) return false ;
			}
		}
		return true ;
	}
	
	
	protected List<Item> children(){
		return null;
	}

	public Object getObj() {
		return obj;
	}

	public void setObj(Object obj) {
		this.obj = obj;
	}

	public JsonKey getKey() {
		return key;
	}

	public void setKey(JsonKey key) {
		this.key = key;
	}

	public void addAction(SelfAction a){
		if(this.readyAction==null){
			this.readyAction = new HashSet<SelfAction>();
		}
		this.readyAction.add(a);
	}
	
	public void addChildrenAction(ChildrenAction a){
		if(this.childrenAction==null){
			this.childrenAction  = new HashSet();
			
		}
		
		this.childrenAction.add(a);
	}

	public Item getParent() {
		return parent;
	}

	public void setParent(Item parent) {
		this.parent = parent;
	}
	
	
	
}
